import json

from flask import current_app, jsonify
from flask_login import login_required, current_user

from . import web
from ..models.base import db
from ..models.wish import Wish
from ..view_models.trade import MyTrades


@web.route('/my/wishes')
@login_required
def my_wishes():
    uid = current_user.id
    wishes_of_mine = Wish.get_user_wishes(uid)
    isbn_list = [gift.isbn for gift in wishes_of_mine]
    wish_count_list = Wish.get_wish_counts(isbn_list)
    my_wishes = MyTrades(wishes_of_mine, wish_count_list)
    return json.dumps(my_wishes.gifts, default=lambda o: o.__dict__)


@web.route('/wish/book/<isbn>')
@login_required
def save_to_wish(isbn):
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
            wish = Wish()
            wish.isbn = isbn
            wish.uid = current_user.id
            db.session.add(wish)
            # db.session.commit()
        return jsonify({'meg': '加入愿望清单成功！'})
    else:
        return jsonify({'meg': '这本书已经加入你的赠送清单或已存在于你的心愿清单'})